package com.distribute.framework.core.lang;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;


@SuppressWarnings({"unchecked","unused","static-access", "serial"})
public class ScriptClassLoader extends URLClassLoader
{	
	String classpath=null;
	
	public ScriptClassLoader(String classpath) throws Exception
	{
		super(new URL[]{new URL("file:"+classpath)},Thread.currentThread().getContextClassLoader());
		this.classpath=classpath;
		System.gc();
	}
	
	public String getClasspath()
	{
		return classpath;
	}

	public Class getClass(String className){
		try{
			File file=new File(classpath+"/"+className.replaceAll("\\.", "/")+".class");
			FileInputStream fis = new FileInputStream(file);
			byte []bytes=new byte[fis.available()];
			byte blocks[] = new byte[1024];
			int nowSize = 0;
			int realRead = 0;
			while ((realRead = fis.read(blocks, 0, 1024)) != -1) {
				System.arraycopy(blocks, 0, bytes, nowSize, realRead);
				blocks = new byte[1024];
				nowSize += realRead;
			}
			fis.close();
			return this.defineClass(className,bytes,0,bytes.length);
		}catch(Exception ex){		
			ex.printStackTrace();
			return null;
		}
	}
	
	public static void nullInstance(Object instance)
	{
	    if (instance == null) {
	      return;
	    }
	    Field[] fields = instance.getClass().getDeclaredFields();
	    for (int i = 0; i < fields.length; ++i) {
	      Field field = fields[i];
	      int mods = field.getModifiers();
	      if (field.getType().isPrimitive()) continue; if (field.getName().indexOf("$") != -1) {
	        continue;
	      }
	      try
	      {
	        field.setAccessible(true);
	        if ((!Modifier.isStatic(mods)) || (!Modifier.isFinal(mods)))
	        {
	          Object value = field.get(instance);
	          if (null != value) {
	            Class valueClass = value.getClass();
	            field.set(instance, null);
	          }
	        }
	      }
	      catch (Throwable t)
	      {
	        t.printStackTrace();
	      }
	    }
	 }
	
}